#include "visionmanager.h"

VisionManager::VisionManager(QObject *parent) : QObject(parent)
    ,visionSession(nullptr)
{
}
bool VisionManager::initialize(){
    visionSession = text_recognition_create_session();
    if(!visionSession) {
        qWarning() << "Vision会话创建失败";
        return false;
    }

    visionConfig = text_recognition_model_config_create();
    text_recognition_model_config_set_name(visionConfig, "vision");
    text_recognition_model_config_set_deploy_type(visionConfig, ModelDeployType::OnDevice);
    text_recognition_set_model_config(visionSession, visionConfig);
    text_recognition_model_config_destroy(&visionConfig);

    text_recognition_result_set_callback(visionSession, &VisionManager::recognitionCallback, this);

    if(text_recognition_init_session(visionSession) != 0) {
        qWarning() << "Vision初始化失败";
        return false;
    }
    return true;
}

VisionManager::~VisionManager()
{
    if(visionSession) {
        text_recognition_destroy_session(&visionSession);
    }
}

void VisionManager::recognizeImage(const QString &imagePath)
{
    if(!QFile::exists(imagePath)) {
        emit recognitionError("图片文件不存在");
        qDebug()<<"图片文件不存在";
        return;
    }

    emit recognitionStarted();
    text_recognition_recognize_text_from_image_file_async(visionSession, imagePath.toUtf8().constData());
}


void VisionManager::recognitionCallback(TextRecognitionResult *result, void *user_data)
{
    VisionManager *manager = static_cast<VisionManager*>(user_data);
    if(!manager) return;

    // 检查错误
    int errorCode = text_recognition_result_get_error_code(result);
    if(errorCode != 0) {
        const char *errorMsg = text_recognition_result_get_error_message(result);
        emit manager->recognitionError(QString::fromUtf8(errorMsg ? errorMsg : "Unknown error"));
        return;
    }

    // 获取识别结果
    const char *text = text_recognition_result_get_value(result);
    if(text) {
        manager->lastRecognitionResult = QString::fromUtf8(text);
        emit manager->recognitionFinished(manager->lastRecognitionResult);
    } else {
        emit manager->recognitionError("未能识别到内容");
    }
}
